#    Copyright 2014 Gregory Roby
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
IncludePath="/opt/coopgis/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)

import djangoproject.settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproject.settings")

#from django.core.management import setup_environ
#import djangoproject.settings
#setup_environ(djangoproject.settings)

from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
import COOPGIS_Ajax, COOPGIS_DynamicTemplate, COOPGIS_FormMisc, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_ReportLabStakerReport
from django.db import transaction
#********************Setup psycopg2 and django section********************

ValidApplicationNames=['Inventory Collection', 'Staker', 'Dynamic Map File Setup']

print Station.objects.all()[0].Point
unit = COOPGISConfig.GetShortDistanceUnit()
print "Distance:  " + str(unit)
from django.contrib.gis.measure import Distance, D
d1 = Distance(**{COOPGISConfig.GetShortDistanceUnit():COOPGISConfig.GetMaximumDistanceToFindNearbyStations()})
print d1
print d1.mi
s = Station.objects.all()[0]

N=Station.objects.filter(Point__distance_lte=(s.Point, d1)).distance(s.Point).order_by('distance')


def RebuildEntireMapSymbology():
    a = Station.objects.all().order_by('id')
    Count = 0
    total = len(a)
    
    for i in a:
        if(Count % 100 == 0):
            print "On :  " + str(Count).ljust(10) + " of:  " + str(total).ljust(10) + "  " + str(datetime.datetime.now())
        i.RebuildSymbology()
        Count = Count + 1


def CreateOutdoorLightReport():
    Circuits = ['602']
    print Circuits
    print "Total:  " + str(Condition.objects.filter(CircuitNumbers__in=Circuits).count())
    print "Not Billed:  " + str(Condition.objects.filter(CircuitNumbers__in=Circuits).filter(OutdoorLightProblemCode__Name='Not Billed').count())
    print "Billed at Wrong Rate:  " + str(Condition.objects.filter(CircuitNumbers__in=Circuits).filter(OutdoorLightProblemCode__Name='Billed at Wrong Rate').count())
    print "Idle, Ballast On:  " + str(Condition.objects.filter(CircuitNumbers__in=Circuits).filter(OutdoorLightProblemCode__Name='Idle, Ballast On').count())
    print "Idle, Ballast Off:  " + str(Condition.objects.filter(CircuitNumbers__in=Circuits).filter(OutdoorLightProblemCode__Name='Idle, Ballast Off').count())
    print "Needs Retirement:  " + str(Condition.objects.filter(CircuitNumbers__in=Circuits).filter(NeedsRetirementIndicator=True).count())
    print "Idle:  " + str(Condition.objects.filter(CircuitNumbers__in=Circuits).filter(OutdoorLightIdleIndicator=True).count())
    
#CreateOutdoorLightReport()


def CoordinatesForSteve__October2012():
    a = StakerWorkOrder.objects.filter(WorkOrderNumber__icontains='20176')
    b = Assembly.objects.filter(CompatibleUnit__PoleIndicator=True).filter(StakerWorkOrder=a[0]).order_by('TagNumber')
    StationOnlyList = []
    Stations=[] #List of Stations, Tag Number
    print "\n\nWork Order 20176"
    for i in b:
        if(i.Station and not i.Station in StationOnlyList):
            Stations.append([i.Station, i.TagNumber])
            StationOnlyList.append(i.Station)
    for i in Stations:
        point = i[0].Point.transform(4326, clone=True)
        print str(i[0].id) + ', ' + i[1] + ', ' + str(point.x) + ' , ' + str(point.y)
    
    print "\n\nWork Order 20125"
    a = StakerWorkOrder.objects.filter(WorkOrderNumber__icontains='20125')
    b = Assembly.objects.filter(CompatibleUnit__PoleIndicator=True).filter(StakerWorkOrder=a[0]).order_by('TagNumber')
    Stations=[] #List of Stations, Tag Number
    StationOnlyList = []
    for i in b:
        if(i.Station and not i.Station in StationOnlyList):
            Stations.append([i.Station, i.TagNumber])
            StationOnlyList.append(i.Station)
    for i in Stations:
        point = i[0].Point.transform(4326, clone=True)
        print str(i[0].id) + ', ' + i[1] + ', ' + str(point.x) + ' , ' + str(point.y)
        

 
def ChangeRotation():
    count = 0
    a = Assembly.objects.all().order_by('id')
    import django.db
    for i in a:
        count = count + 1
        if(count % 500 == 0):
            print "on:  " + str(count) + '  of' + str(len(a))
            django.db.reset_queries()
        i.Rotation = 360 - i.Rotation
        i.save()
        



import djangoproject.models.cis
def MatchMeters():
    djangoproject.models.cis.UpdateMeterNumbersFromOMS()

import COOPGIS_FormStaker
li=[1]
def TestGenerateAllReports(Input=0):
    a = StakerWorkOrder.objects.filter(ArchivedIndicator=False
        ).exclude(DeletedIndicator=True).filter(id__gte=Input).order_by('id')
    for i in a:
        print i.id
        li[0] = i
        COOPGIS_FormStaker.GenerateReportDetails(i.id, 'groby')




def TestBank():
    a = Assembly.objects.filter(TransformerBank__id__gte=1)
    b = []
    for i in a:
        if(i.TransformerBank.TransformerBankType.Name == 'Wye'):
            b.append(i)
    for i in b:
        i.Station.RebuildSymbology()


class AMRMatch():
   def __init__(self, AMRSerialNumber, AMRPhase, Phase, Station):
       self.AMRSerialNumber=AMRSerialNumber
       self.AMRPhase=self.ConvertAMRPhase(AMRPhase)
       self.Phase=Phase
       self.Station=Station
   def ConvertAMRPhase(self, AMRPhase):
       if(AMRPhase == 1):
           return 'A'
       elif(AMRPhase == 2):
           return 'B'
       elif(AMRPhase == 3):
           return 'C'
       else:
           raise(Exception('Invalid Phase'))

MatchingMeterDict={}

def UpdateOldMapNumberFromOMS():
    """UpdateOldMapNumberFromOMS will look for meters in the GIS with a Map Number
       of '0' and check to see if the OMS has a Map Number for the Meter,
       based on the DCSI Number"""
    Meters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True).filter(OldMapNumber='0')
    MetersAtStart=Meters.count()
    Fixed=0
    for i in Meters:
        if(len(i.MeterDCSINumber) > 5):
            OMSMeter=OMS.Meter.objects.filter(MeterNumber__contains=i.MeterDCSINumber)
            if(not OMSMeter):
                continue
            else:
                OMSMeter=OMSMeter[0]
            PotentialMapNumber=OMSMeter.GetShortMapNumber()
            if(PotentialMapNumber == 'UNKNOWN'):
                continue
            i.OldMapNumber=PotentialMapNumber
            i.save()
            i.Station.RebuildSymbology()
            Fixed=Fixed + 1
            if (Fixed % 10 == 0):
                print str(Fixed) + '   Fixed.'
    print "Starting Meters With Map Number of '0':"  + str(MetersAtStart)
    print "Meters with new map numbers:  " + str(Fixed)
    Meters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True).filter(OldMapNumber='0')
    MetersAtEnd=Meters.count()
    print "Ending Meters With Map Number of '0':"  + str(MetersAtEnd)
    

    
def GetDigitsOnly(String):
    NewStringList=[]
    for i in String:
        if(i in ['1', '2', '3', '4', '5', '6', '7', '8', '9']):
            NewStringList.append(i)
    return ''.join(NewStringList)
    

    
def GetCSVCommands():
    FileName='/home/technology/Desktop/commandoutput_03_29_2010.csv'
    StartDate=datetime.datetime(2010, 03, 01)
    Results=[]
    Commands1=Command.objects.filter(CommandUserName='felkeld').filter(CommandCreateDateTime__gte=StartDate).order_by('Order')
    Commands2=Command.objects.filter(CommandUserName='wiless').filter(CommandCreateDateTime__gte=StartDate).order_by('Order')
    for i in Commands1:
        Results.append(str(i.Name) + ', ' + str(i.CommandUserName) + ', ' + str(i.CommandCreateDateTime) + ', ' + str(i.AssemblyName) + '\n')
    for i in Commands2:
        Results.append(str(i.Name) + ', ' + str(i.CommandUserName) + ', ' + str(i.CommandCreateDateTime) + ', ' + str(i.AssemblyName) + '\n')
    File=open(FileName, 'w')
    File.writelines(Results)
    File.close()

def GetMeterInfo():
    a = Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    FileName='/home/coopgisadmin/Desktop/Meters.csv'
    File=open(FileName, 'w')
    Results=[]
    for i in a:
        Results.append(str(i.Station.id) + ',' + str(i.OldMapNumber) + ',' + str(i.CircuitNumber) + '\n')
    File.writelines(Results)
    File.close()
                       
def CopperAdd():
    #FourPoundsCopper=['P30-3', 'P30-4', 'P30-5', 'P30-6', 'P30-7', 'P35-3', 'P35-4', 'P35-5', 'P35-6', 'P35-7', 'P40-3', 'P40-4', 'P40-5', 'P40-6', 'P40-7']
    FivePoundsCopper=['P45-2', 'P45-3', 'P45-4', 'P45-5', 'P45-6', 'P45-7', 'P50-2', 'P50-3', 'P50-4', 'P50-5']
    #SixPoundsCopper=['P55-2', 'P55-3', 'P55-4', 'P55-5', 'P55-6', 'P60-2', 'P60-3', 'P60-4', 'P60-5']
    #FixCopperPoles(FourPoundsCopper, 4)
    FixCopperPoles(FivePoundsCopper, 5)
    #FixCopperPoles(SixPoundsCopper, 6)

def FixCopperPoles(ListOfPoleClasses, NumberOfCopperAssemblies):
    InstallCutOffDate=datetime.date(2011, 01, 18)
    Poles = []
    PrintCount = 0
    for poleClass in ListOfPoleClasses:

        Temp=Assembly.objects.filter(CompatibleUnit__Name=poleClass)
        for i in Temp:
            Poles.append(i)
    for pole in Poles:
        PrintCount = PrintCount + 1
        if(PrintCount % 100 == 0): 
            print "On pole:  " + str(pole.CompatibleUnit.Name) + '  ' + str(pole.Station.id)
        proceed=MakeSureNoCopperAtPole(pole)
        if not proceed:
            #print "Skipping pole because copper is already there."
            continue
        SoftDrawnCopperIndicator=MakeSureInstalledBefore(pole, InstallCutOffDate)
        if not SoftDrawnCopperIndicator:
            #print "Adding Copper to pole: M2-6CW"
            for i in range (0, NumberOfCopperAssemblies):
                CreateCopperAssembly(pole, 'M2-6CW')
        else:
            #print "Adding Copper to pole:  M2-6SD"
            for i in range (0, NumberOfCopperAssemblies):
                CreateCopperAssembly(pole, 'M2-6SD')

def CreateCopperAssembly(pole, AssemblyName):
    if(pole.StakerWorkOrder):
        StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=pole.StakerWorkOrder.GetCommandidData()
    else:
        StakerWorkOrderid=None
        StakerWorkOrderIndexWhenReverseSorted=-1
    try:
        InstallStatusName=pole.InstallStatus.Name
    except:
        InstallStatusName='Existing'

    command=Command()
    command=command.Create(Name='CreateStationAssembly', AssemblyName=AssemblyName, StartPoint=pole.Station.Point, TagNumber='', 
                           PutIntoServiceDate=pole.PutIntoServiceDate, PrimaryIndicator=pole.PrimaryIndicator, SecondaryIndicator=pole.SecondaryIndicator, 
                           PoleStubIndicator=False, PoleLightIndicator=False, PoleGuyIndicator=False, 
                           PoleMeterIndicator=False, OwnerName='', ManufacturerName='', 
                           MeterFormName='', OpenIndicator='', Rotation=pole.Rotation,  
                           MeterOnPoleIndicator=False, PhaseAIndicator=pole.PhaseAIndicator, PhaseBIndicator=pole.PhaseAIndicator,
                           PhaseCIndicator=pole.PhaseCIndicator, PhaseNeutralIndicator=pole.PhaseNeutralIndicator, CircuitNumber=pole.CircuitNumber,
                           SerialNumber=pole.SerialNumber, MeterNumber=pole.MeterNumber, MeterDCSINumber=pole.MeterDCSINumber, OldMapNumber=pole.OldMapNumber,
                           ServiceIndicator=pole.ServiceIndicator, MeterServiceTypeName='', CommandUserName='wiser',
                           CommandReadyToProcessIndicator=True, PhysicalAddress=pole.PhysicalAddress, IdleIndicator=pole.IdleIndicator, 
                           InstallStatus=InstallStatusName, StakerWorkOrderid=StakerWorkOrderid, 
                           StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted)
    command.save()
    command.Process(RebuildSymbologyIndicator=False)

 
def MakeSureNoCopperAtPole(pole):
    count = Assembly.objects.filter(Station=pole.Station).filter(CompatibleUnit__Name='M2-6SD').count() +\
            Assembly.objects.filter(Station=pole.Station).filter(CompatibleUnit__Name='M2-6CW').count() +\
            Assembly.objects.filter(Station=pole.Station).filter(CompatibleUnit__Name='M2-4SD').count() +\
            Assembly.objects.filter(Station=pole.Station).filter(CompatibleUnit__Name='M2-4CW').count()
    if(count):
        return False
    else:
        return True

def MakeSureInstalledBefore(Pole,InstallCutoffDate):
    if Pole.StakerWorkOrder and Pole.StakerWorkOrder.ArchivedDate:
        if Pole.StakerWorkOrder.ArchivedDate<InstallCutoffDate:
            return True
        else:
            return False
    else:
        return True


def FixNonMeterMapNumbers():
    Meters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    Count = 0
    for meter in Meters:
        if( (len(meter.OldMapNumber) < 4 ) and (Assembly.objects.filter(Station=meter.Station).filter(CompatibleUnit__MeterIndicator=True).count() == 1) ):
            Assemblies=Assembly.objects.filter(Station=meter.Station).exclude(CompatibleUnit__MeterIndicator=True)
            for assembly in Assemblies:
                if(assembly.OldMapNumber):
                    print "For Station:  " + str(meter.Station.id) + '   Would change meter map number:  ' + str(meter.OldMapNumber) +\
                           "   to:  " + str(assembly.OldMapNumber).upper()
                    Count = Count + 1
                    meter.OldMapNumber = assembly.OldMapNumber
                    meter.save()
                    assembly.OldMapNumber = ''
                    assembly.save()
                    
    print "Changes made:  " + str(Count)



def RebuildMeterSymbology():
    Count = 0
    Meters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    for meter in Meters:
        meter.Station.RebuildSymbology()
        Count = Count + 1
        if(Count == 5):
            Count = 0
            print meter.Station.id
            

def PopulateOptimumObjectReference():
    import AMR, CIS
    Meters=AMR.Serialnumber.objects.all()
    for meter in Meters:
        UpdateIndicator=False
        NewIndicator=False
        CISMeter=CIS.Meterdetl.objects.filter(meter=str(meter.serialnumber).rjust(12, '0'))
        if(not CISMeter):
            print "No Meter Found in CIS for:  " + str(meter.serialnumber)
            continue
        elif(len(CISMeter) > 1):
            print "Multiple Meters Found in CIS for:  " + str(meter.serialnumber)
            continue
        else:
            CISMeter=CISMeter[0]
        try:
            AMROptimumObjectReference=AMR.OptimumObjectReference.objects.filter(serialnumber=CISMeter.amrid[2:].strip())
        except:
            print "CIS Meter found with invalid AMRid:  " + str(meter.serialnumber)
            continue
        if(AMROptimumObjectReference):
            AMROptimumObjectReference=AMROptimumObjectReference[0]
            if(not AMROptimumObjectReference.meternumber ==  CISMeter.meter.lstrip('0')):
                print "An Error Occurred:  AMROptimumObjectReference.meternumber ==  CISMeter.meter.lstrip('0'):  " + str(AMROptimumObjectReference.meternumber) + '        ' + str(CISMeter.meter.lstrip('0'))
                raise(Exception("An Error Occurred:  AMROptimumObjectReference.meternumber ==  CISMeter.meter.lstrip('0'):  " + str(AMROptimumObjectReference.meternumber) + '        ' + str(CISMeter.meter.lstrip('0'))))
            if(not str(AMROptimumObjectReference.serialnumber) == CISMeter.amrid[2:].strip()):
                AMROptimumObjectReference.serialnumber = int(CISMeter.amrid[2:].strip())
                raise('Here')
                UpdateIndicator=True
            if(not AMROptimumObjectReference.utilacctid == 1):
                AMROptimumObjectReference.utilacctid=1
                UpdateIndicator=True
            if(not AMROptimumObjectReference.meter_objectid == CISMeter.amrid[2:].strip()):
                AMROptimumObjectReference.meter_objectid = CISMeter.amrid[2:].strip()
                UpdateIndicator=True
            if(not AMROptimumObjectReference.servicelocation_objectid == CISMeter.location.lstrip('0')):
                AMROptimumObjectReference.servicelocation_objectid = CISMeter.location.lstrip('0')
                UpdateIndicator=True
            if(not AMROptimumObjectReference.customer_objectid == CISMeter.mbrsep.lstrip('0')[:-3]):
                AMROptimumObjectReference.customer_objectid = CISMeter.mbrsep.lstrip('0')[:-3]
                UpdateIndicator=True
        else:
            #otherwise, create a new OptimumObjectReference
            AMROptimumObjectReference=AMR.OptimumObjectReference()
            AMROptimumObjectReference.meternumber=CISMeter.amrid[2:].strip()
            AMROptimumObjectReference.serialnumber=int(CISMeter.amrid[2:].strip())
            AMROptimumObjectReference.utilacctid=int(1)
            AMROptimumObjectReference.meter_objectid=CISMeter.amrid[2:].strip()
            AMROptimumObjectReference.servicelocation_objectid =CISMeter.location.lstrip('0')
            AMROptimumObjectReference.customer_objectid = CISMeter.mbrsep.lstrip('0')[:-3]
            
            UpdateIndicator=True
            NewIndicator=True
        if(UpdateIndicator):
            AMROptimumObjectReference.updated_at = datetime.datetime.now().date()
            AMROptimumObjectReference.save()
            try:
                django.db.connections['amr'].commit()
            except:
                pass

     


def PrintNonMatchedAMRServiceLocations():
    import AMR, CIS
    Meters=AMR.Serialnumber.objects.all()
    for meter in Meters:
        #if(AMR.OptimumObjectReference.objects.filter(serialnumber=meter.serialnumber)):
        #    continue  #Do not add meters already in the optimum_object_reference table
        ServiceLocation=CIS.Locationdetl.objects.filter(meter=str(meter.serialnumber).rjust(12, '0')).filter(discdate='000000')
        if(not ServiceLocation):
            print "No Service Location found for:  " + str(meter.serialnumber)
            continue
        else:
            ServiceLocation=ServiceLocation[0]
        if(not ServiceLocation.location.lstrip('0') == meter.premiseid):
            print "Meter:  " + str(meter.serialnumber) + '    should be at Location:  ' + ServiceLocation.location.lstrip('0') + '   but is at Location:  ' + str(meter.premiseid)
            



def PrintCISMetersMissingAMRInfo():
    import CIS
    Meters=CIS.Meterdetl.objects.all()
    


def UpdateTransformerUsageAnalysis():
    import datetime
    Cache=AMRDBCache()
    print "Deleting Old Transformer Usage Analysis Objects:  " + str(TransformerUsageAnalysis.objects.count())
    TransformerUsageAnalysis.objects.all().delete()
    print "Deletion Completed."
    startdate=datetime.datetime.today() - datetime.timedelta(days=1)
    Transformers = Assembly.objects.filter(CompatibleUnit__TransformerIndicator=True)
    count = 0
    TimeClock=datetime.datetime.now()
    for transformer in Transformers:
        TransformerUsageAnalysis().PerformAnalysis(transformer, startdate, Cache)
        count= count + 1
        Current = datetime.datetime.now()
        print str(Current - TimeClock) + ":    " +  "On:  " + str(count) + '  of  ' + str(len(Transformers))
        TimeClock=Current


def PrintMaxSpan():
    Spans=Span.objects.all()
    MaxLength=0
    MaxSpan=None
    for span in Spans:
        if(span.Line.length > MaxLength):
            MaxLength=span.Line.length
            MaxSpan=span
    print MaxLength
    print MaxSpan

def ManyUnitSpans():
    Spans=Span.objects.all()
    MaxUnits=10
    for span in Spans:
        if(Assembly.objects.filter(Span=span).count() > MaxUnits):
            print str(span.id).ljust(20) + str(Assembly.objects.filter(Span=span).count())


def GetNumberOfWiresInSpan(unit, span):
    Multiplier=0
    Assemblies=Assembly.objects.filter(Span=span).filter(CompatibleUnit=unit)
    for i in Assemblies:
        if(i.PhaseAIndicator):
            Multiplier = Multiplier + 1
        if(i.PhaseBIndicator):
            Multiplier = Multiplier + 1
        if(i.PhaseCIndicator):
            Multiplier = Multiplier + 1
        if(i.PhaseNeutralIndicator):
            Multiplier = Multiplier + 1
    return Multiplier

def CalculateSpanTemp():
    Spans = Span.objects.all()
    unit=CompatibleUnit.objects.filter(Name='4 ACSR')[0]
    unit2=CompatibleUnit.objects.filter(Name__icontains='336.4')[0]
    print unit
    print unit2
    Count = 1
    for span in Spans:
        span.TempNumberOfFourACSR=GetNumberOfWiresInSpan(unit, span)
        span.TempNumberOfThreeThreeSixACSR=GetNumberOfWiresInSpan(unit2, span)
        span.save()
        Count = Count + 1
        if(Count % 100 == 0):
            print ' On:  ' + str(Count) + '  of   ' + str(len(Spans))
        
def ConvertTransformer():
    OldTransformer=CompatibleUnit.objects.filter(Name='VG15')[0]
    NewTransformer=CompatibleUnit.objects.filter(Name='VG15C')[0]
    CutOut=CompatibleUnit.objects.filter(Name='VM5-9TR')[0]
    Transformers=Assembly.objects.filter(CompatibleUnit=OldTransformer)
    for i in Transformers:
        CutOuts=Assembly.objects.filter(Station=i.Station).filter(CompatibleUnit=CutOut)
        if(CutOuts):
            CutOuts[0].delete()
            i.CompatibleUnit=NewTransformer
            i.save()
        

#test
#a = Assembly.objects.filter(MeterDCSINumber=13998099)[0]    
#import djangoproject.views.GISReport
#djangoproject.views.GISReport.WalkSinglePhaseLines(a)


def TestSpeeds():
    a = datetime.datetime.now()
    print Command.objects.order_by('-Order')[0].Order + 1
    b = datetime.datetime.now()
    print b-a
    print
    from django.db.models import Max
    a = datetime.datetime.now()
    print Command.objects.all().aggregate(Max('Order'))['Order__max'] + 1
    b = datetime.datetime.now()
    print b-a

def GetWPSpansFeedLight():
    WPAssemblies=Assembly.objects.filter(CompatibleUnit__Name__icontains='w.p.').order_by('id')
    Results=[]
    for i in WPAssemblies:
        if (Assembly.objects.filter(CompatibleUnit__LightIndicator=True).filter(Station=i.Span.StartStation).count() or
            Assembly.objects.filter(CompatibleUnit__LightIndicator=True).filter(Station=i.Span.EndStation).count()):
            if not i.Span in Results:
                Results.append(i.Span)
            
    return Results

def WalkWPSpansThatFeedLight(WPAssembly):
    CurrentSpan=WPAssembly
    AssembliesWalked=[]
    SpansVisited=[]
    SpansToVisit=[]
    while True:
        for assembly in Assembly.objects.filter(Span=CurrentSpan).filter(CompatibleUnit__Name__icontains='w.p.'):
            AssembliesWalked.append(assembly)
        if (Assembly.objects.filter(CompatibleUnit__TransformerIndicator=True).filter(Station=CurrentSpan.StartStation).count() or
            Assembly.objects.filter(CompatibleUnit__MeterIndicator=True).filter(Station=CurrentSpan.StartStation).count()):
            pass
        else:
            PotentialSpans=CurrentSpan.StartStation.GetNearbySpans()
            for span in PotentialSpans:
                if (Assembly.objects.filter(Span=span).filter(CompatibleUnit__Name__icontains='w.p.').count()
                    and not span in SpansVisited and not span==CurrentSpan):
                    SpansToVisit.append(span)
        if (Assembly.objects.filter(CompatibleUnit__TransformerIndicator=True).filter(Station=CurrentSpan.EndStation).count() or
            Assembly.objects.filter(CompatibleUnit__MeterIndicator=True).filter(Station=CurrentSpan.EndStation).count()):
            pass
        else:
            PotentialSpans=CurrentSpan.EndStation.GetNearbySpans()
            for span in PotentialSpans:
                if (Assembly.objects.filter(Span=span).filter(CompatibleUnit__Name__icontains='w.p.').count()
                    and not span in SpansVisited and not span==CurrentSpan):
                    SpansToVisit.append(span)
        SpansVisited.append(CurrentSpan)
        if SpansToVisit:
            CurrentSpan=SpansToVisit.pop()
        else:
            break
    return AssembliesWalked

def ConvertWPto6Duplex():
    WPSpans=GetWPSpansFeedLight()
    unit=CompatibleUnit.objects.filter(Name='6 DUPLEX')[0]
    for span in WPSpans:
        AssembliesWalked=WalkWPSpansThatFeedLight(span)
        for assembly in AssembliesWalked:
            print str(assembly.Span.id).ljust(15) + str(assembly.id).ljust(15) + str(assembly.CompatibleUnit.Name).ljust(30) + str(unit.Name)
            assembly.CompatibleUnit=unit
            assembly.save()
            assembly.Span.RebuildSymbology()

def PrintCounty(Meter):
    Counties=County.objects.all()
    MeterPoint=Meter.Station.Point.transform(4326, clone=True)
    for i in Counties:
        if(MeterPoint.within(i.Border)):
            print i.Name
            
def WrongCircuitNumbers():
    import os
    os.chdir('/home/technology/Desktop')
    output = open('CircuitNumberReport.txt', 'w')
    WrongNumbers = [0, 1, 25, 84, 1305, 1306, 5032, 9999]
    Assemblies = Assembly.objects.filter(CircuitNumber__in=WrongNumbers)
    for i in Assemblies:
        if i.Span:
            output.write(str(i.id) + '; Circuit: ' + str(i.CircuitNumber) + '; Span: ' + str(i.Span.id) + '\r\n')
        elif i.Station:
            output.write(str(i.id) + '; Circuit: ' + str(i.CircuitNumber) + '; Station: ' + str(i.Station.id) + '\r\n')
    output.close()
        
def URDMarkerPrimarySecondary():
    URDs = Assembly.objects.filter(CompatibleUnit__URDMarkerIndicator=True).exclude(PrimaryIndicator=True).exclude(SecondaryIndicator=True).exclude(ServiceIndicator=True)
    for urd in URDs:
        Station = urd.Station
        Spans = Span.objects.filter(StartStation=Station)| Span.objects.filter(EndStation=Station)
        SpanAssemblies = Assembly.objects.filter(Span__in=list(Spans))
        PrimaryCount = 0
        SecondaryCount = 0
        ServiceCount = 0
        for i in SpanAssemblies:
            if i.PrimaryIndicator:
                PrimaryCount+=1
            elif i.SecondaryIndicator:
                SecondaryCount+=1
            elif i.ServiceIndicator:
                ServiceCount+=1
        if PrimaryCount:
            urd.PrimaryIndicator=True
            urd.save()
        elif SecondaryCount:
            urd.SecondaryIndicator=True
            urd.save()
        elif ServiceCount:
            urd.ServiceIndicator=True
            urd.save()
            
def FixUnitsTwo():
    Assemblies = Assembly.objects.filter(CompatibleUnit__Name__in=['M2-2', 'E3-10']).exclude(
        PrimaryIndicator=True).exclude(SecondaryIndicator=True).exclude(ServiceIndicator=True)
    count=0
    for i in Assemblies:
        count+=1
        if count %1000==0:
            print count
        Stations = Assembly.objects.filter(Station=i.Station)
        Primary = Stations.filter(PrimaryIndicator=True).count()
        Secondary = Stations.filter(SecondaryIndicator=True).count()
        if Primary and not Secondary:
            i.PrimaryIndicator=True
            i.save()
        elif Secondary and not Primary:
            i.SecondaryIndicator=True
            i.save()

def FixUnitsThree():
    Assemblies = Assembly.objects.filter(CompatibleUnit__Name__in=['M2-2', 'M2-12']).exclude(
        PrimaryIndicator=True).exclude(SecondaryIndicator=True).exclude(ServiceIndicator=True)
    print Assemblies.count()
    for i in Assemblies:
        Poles = Assembly.objects.filter(CompatibleUnit__PoleIndicator=True).filter(Station=i.Station)
        if not Poles.count() == 1:
            continue
        Pole=Poles[0]
        if Pole.PrimaryIndicator:
            i.PrimaryIndicator=True
            i.save()
        elif Pole.SecondaryIndicator:
            i.SecondaryIndicator=True
            i.save()
    Assemblies2=Assembly.objects.filter(CompatibleUnit__StakerGuyMarkerIndicator=True).exclude(
        PrimaryIndicator=True).exclude(SecondaryIndicator=True).exclude(ServiceIndicator=True)
    print Assemblies2.count()
    for i in Assemblies2:
        Stations = Assembly.objects.filter(Station=i.Station)
        Guy = Stations.filter(CompatibleUnit__StakerGuyGuyIndicator=True)
        Anchor = Stations.filter(CompatibleUnit__StakerGuyAnchorIndicator=True)
        if not Anchor.count():
            print 'No Anchor'
            continue
        if not Guy.count():
            print 'No Guy'
            continue
        Total = Guy.count() + Anchor.count()
        g = Guy[0]
        a = Anchor[0]
        if g.PrimaryIndicator and a.PrimaryIndicator:
            i.PrimaryIndicator=True
            i.save()
        elif g.SecondaryIndicator and a.SecondaryIndicator:
            i.SecondaryIndicator=True
            i.save()
        elif not g.PrimaryIndicator and not g.SecondaryIndicator and not g.ServiceIndicator:
            print g.CompatibleUnit.Name

            
        
